import 'package:banquanjie_app/app/services/screenAdapter.dart';
import 'package:flutter/material.dart';

class DropDownMenuController {
  _DropDownMenuState? _state;

  void _attach(_DropDownMenuState state) {
    _state = state;
  }

  void close() {
    _state?._removeDropdown();
  }

  void _detach() {
    _state = null;
  }
}

class DropDownMenu extends StatefulWidget {
  final List<String> items;
  final List<Widget> dropItems;
  final Color? backgroundColor;
  final Color? selectedColor;
  final Color? textColor;
  final double? itemHeight;
  // final double? maxDropHeight;
  final Color? overlayColor;
  final Function ? closeCallBack; 
  final DropDownMenuController? controller;

  const DropDownMenu({
    super.key, 
    required this.items,
    required this.dropItems,
    this.backgroundColor = Colors.white,
    this.selectedColor = const Color(0xff00b277),
    this.textColor = Colors.black,
    this.itemHeight = 44.0,
    // this.maxDropHeight,
    this.overlayColor,
    this.closeCallBack,
    this.controller,
  }) : assert(items.length == dropItems.length);

  @override
  State<DropDownMenu> createState() => _DropDownMenuState();
}

class _DropDownMenuState extends State<DropDownMenu> {
  int? _selectedIndex;
  final LayerLink _layerLink = LayerLink();
  OverlayEntry? _overlayEntry;

  @override
  void initState() {
    super.initState();
    widget.controller?._attach(this);
  }

  @override
  Widget build(BuildContext context) {
    return CompositedTransformTarget(
      link: _layerLink,
      child: Container(
        color: widget.backgroundColor,
        height: widget.itemHeight,
        child: Row(
          children: List.generate(widget.items.length, (index) {
            final isSelected = _selectedIndex == index;
            return Expanded(
              child: GestureDetector(
                onTap: () => _toggleDropdown(index),
                child: Container(
                  height: widget.itemHeight,
                  decoration: BoxDecoration(
                    border: Border(
                      // bottom: BorderSide(
                      //   color: isSelected
                      //       ? widget.selectedColor ?? Colors.orange
                      //       : Colors.grey[200]!,
                      //   width: isSelected ? 2.0 : 1.0,
                      // ),
                    ),
                  ),
                  child: Center(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          widget.items[index],
                          style: TextStyle(
                            fontSize: ScreenAdapter.fontSize(28),
                            fontWeight: FontWeight.w500,
                            color: isSelected
                                ? widget.selectedColor
                                : widget.textColor ,
                          ),
                        ),
        
                        Icon(
                          isSelected
                              ? Icons.arrow_drop_up_rounded
                              : Icons.arrow_drop_down_rounded,
                          color: isSelected
                              ? widget.selectedColor
                              : widget.textColor,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            );
          }),
        ),
      ),
    );
  }

  void _toggleDropdown(int index) {
    if (_selectedIndex == index) {
      // 如果点击的是已选中的选项，则关闭下拉
      _onCloseDropDownMenu();
    } else {
      _removeDropdown();
      // 否则打开新的下拉
      _selectedIndex = index;
      _showDropdown();
    }
  }

  void _showDropdown() {

    // final screenHeight = MediaQuery.of(context).size.height;
    final screenWidth = MediaQuery.of(context).size.width;
    // final maxDropHeight = widget.maxDropHeight ?? screenHeight * 0.6;
    // ignore: deprecated_member_use
    final overlayColor = widget.overlayColor ?? Colors.black.withOpacity(0.5);

    // 获取组件的位置
    final renderBox = context.findRenderObject() as RenderBox?;
    if (renderBox == null) return;
    
    final position = renderBox.localToGlobal(Offset.zero);
    final filterBarHeight = position.dy + widget.itemHeight!;

    _overlayEntry = OverlayEntry(
      builder: (context) {
        return Stack(
          children: [
            // 全屏半透明遮罩层 - 从下拉菜单底部开始
            Positioned(
              left: 0, // 屏幕最左侧
              top: filterBarHeight,
              right: 0, // 屏幕最右侧
              bottom: 0,
              child: GestureDetector(
                onTap: _onCloseDropDownMenu,
                behavior: HitTestBehavior.opaque,
                child: Container(color: overlayColor),
              ),
            ),
            // 全屏宽度下拉内容
            Positioned(
              left: 0, // 屏幕最左侧
              right: 0, // 屏幕最右侧
              top: filterBarHeight,
              child: Material(
                color: Colors.white,
                elevation: 4,
                child: ConstrainedBox(
                  constraints: BoxConstraints(
                    // maxHeight: maxDropHeight,
                    maxWidth: screenWidth,
                  ),
                  // child: SingleChildScrollView(
                  //   physics: const ClampingScrollPhysics(),
                  //   child: SizedBox(
                  //     width: screenWidth,
                  //     child: widget.dropItems[_selectedIndex!],
                  //   ),
                  // ),
                  child: SizedBox(
                    width: screenWidth,
                    child: widget.dropItems[_selectedIndex!],
                  ),
                ),
              ),
            ),
          ],
        );
      },
    );

    Overlay.of(context).insert(_overlayEntry!);
  }

  void _onCloseDropDownMenu() { 
    _removeDropdown();
    if (widget.closeCallBack != null) {
      widget.closeCallBack!();
    }
  }

  void _removeDropdown() {
    _overlayEntry?.remove();
    _overlayEntry = null;
    _selectedIndex = -1;
    setState(() {});
  }

  @override
  void dispose() {
    widget.controller?._detach();
    _removeDropdown();
    super.dispose();
  }

 
  
}